use atlas
go
UPDATE [monitor400_tmp]
SET [monitor400_tmp].hostname = RTRIM([monitor400_tmp].hostname),
    [monitor400_tmp].from_surname = RTRIM([monitor400_tmp].from_surname),
    [monitor400_tmp].from_x400 = RTRIM([monitor400_tmp].from_x400),
    [monitor400_tmp].to_surname = RTRIM([monitor400_tmp].to_surname),
    [monitor400_tmp].to_x400 = RTRIM([monitor400_tmp].to_x400),
    [monitor400_tmp].msg_id = RTRIM([monitor400_tmp].msg_id),
    [monitor400_tmp].alias_sender = RTRIM([monitor400_tmp].alias_sender),
    [monitor400_tmp].msg_errorcode = RTRIM([monitor400_tmp].msg_errorcode)
go
INSERT INTO mon400_aliases (item)
 (SELECT DISTINCT monitor400_tmp.alias_sender FROM monitor400_tmp
    WHERE monitor400_tmp.alias_sender NOT IN (SELECT item FROM mon400_aliases))
go
INSERT INTO mon400_errorcodes (item)
 (SELECT DISTINCT monitor400_tmp.msg_errorcode FROM monitor400_tmp
    WHERE monitor400_tmp.msg_errorcode NOT IN (SELECT item FROM mon400_errorcodes))
go
INSERT INTO mon400_abonents (mon400_abonents.surname, mon400_abonents.x400)
 (SELECT DISTINCT monitor400_tmp.from_surname, monitor400_tmp.from_x400 FROM monitor400_tmp
  WHERE (monitor400_tmp.msg_errorcode = 'OK') AND 
        (monitor400_tmp.from_surname NOT IN 
          (SELECT mon400_abonents.surname FROM mon400_abonents)))
go
INSERT INTO mon400_abonents (mon400_abonents.surname, mon400_abonents.x400)
 (SELECT DISTINCT monitor400_tmp.to_surname, monitor400_tmp.to_x400 FROM monitor400_tmp
  WHERE (monitor400_tmp.msg_errorcode = 'OK') AND 
        (monitor400_tmp.to_surname NOT IN 
          (SELECT mon400_abonents.surname FROM mon400_abonents)))
go